package com.example.myapp.api;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static Map<String,Object> mParams;
    public  static  Api api=new Api();
    public Api(){

    }
    public  static  Api  config(String url,Map<String,Object> params){
        client=new OkHttpClient.Builder().build();
        requestUrl= ApiConfig.BASE_URL+url;
        mParams=params;
        return  api;
    }
    public  void  postRequest(ResponseCallback callback){
        JSONObject jsonObject=new JSONObject(mParams);
        String jsonStr=jsonObject.toString();
        RequestBody requestBody=
                RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonStr);
        Request request=new Request.Builder()
                .url(requestUrl)
                .addHeader("contentType","application/json;charset=utf-8")
                .post(requestBody)
                .build();
        final Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

               callback.OnFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                callback.OnSuccess(result);

            }
        });
    }
    public void  getRequest(ResponseCallback responseCallback){

    }
}
